/**
 * @fileoverview Giant Interective Group, Inc. Javascript Library v#version.
 * 该Javascript UI库是基于jQuery的扩展。
 * * <pre>
 * Copyright (C) 2004-2009 Giant Interective Group, Inc. All rights reserved.
 * 版权所有 2004-2009 上海巨人网络科技有限公司
 * </pre>
 * @version #version, #date
 * @author  Zhangkai
 * Depend on jQuery 1.3.x
 */
if (typeof giant === 'undefined')
    var giant = {};

if (typeof giant.ui === 'undefined')
    giant.ui = {};
(function($) {
    var opts = null;
    var datas = null;
    var pictureArr = null;
    var activeNumber = 0;
    var isBigImageLoad = false;
    var isScroll = false;
     /**
     * 创建个新的giant.ui.album实例。
     * @giant.ui.album 相册组件。
     * @constructor
     * @returns {giant.ui.album}
     * @example
     *<pre>
     * //以下代码放在body里
     *  &lt;div class=&quot;mauto w650 clearfix tcenter big_image_wrapper&quot;&gt;
     *      &lt;img src=&quot;&quot; id=&quot;big_image&quot; alt=&quot;&quot;/&gt;
     *      &lt;a id=&quot;btn_prev&quot; title=&quot;上一张&quot; class=&quot;btn-prev&quot; href=&quot;javascript:void(1)&quot;&gt;&lt;/a&gt;
     *      &lt;a id=&quot;btn_next&quot; title=&quot;下一张&quot; class=&quot;btn-next&quot; href=&quot;javascript:void(1)&quot;&gt;&lt;/a&gt;
     *
     *      &lt;div class=&quot;loading-2&quot; id=&quot;image-loading&quot;&gt;
     *          &lt;img title=&quot;图片下载中&quot; width=&quot;120px&quot; height=&quot;15px&quot;
     *              alt=&quot;图片下载中&quot;
     *              src=&quot;../../images/module/loading-2.gif&quot;/&gt;
     *      &lt;/div&gt;
     *  &lt;/div&gt;
     * &lt;div class=&quot;mauto mt20 w600 llight1 clearfix&quot;&gt;
     *      &lt;div class=&quot;tright&quot;&gt;
     *          &lt;span id=&quot;current_num&quot;&gt;&lt;/span&gt;/&lt;span id=&quot;total_num&quot;&gt;15&lt;/span&gt;
     *      &lt;/div&gt;
     *      &lt;div&gt;照片名称：&lt;span id=&quot;img_title_container&quot;&gt;&lt;/span&gt;&lt;/div&gt;
     *      &lt;div&gt;照片描述：&lt;span id=&quot;img_remark_container&quot;&gt;&lt;/span&gt;&lt;/div&gt;
     *  &lt;/div&gt;
     * &lt;div class=&quot;mauto mt15 ml15 clearfix&quot;&gt;
     *      &lt;div class=&quot;fleft&quot;&gt;&lt;a href=&quot;javascript:void(1)&quot; id=&quot;btn_left_album&quot; title=&quot;&quot;class=&quot;gr-pic-left&quot;&gt;&lt;/a&gt;&lt;/div&gt;
     *      &lt;div class=&quot;gr-pic-list-wrapper&quot;&gt;
     *          &lt;ul class=&quot;fleft gr-pic-list clearfix&quot; id=&quot;small_image_container&quot;&gt;&lt;/ul&gt;
     *   &lt;/div&gt;
     *      &lt;div class=&quot;fleft&quot;&gt;
     *          &lt;a href=&quot;javascript:void(1)&quot; id=&quot;btn_right_album&quot; title=&quot;&quot; class=&quot;gr-pic-right&quot;&gt;&lt;/a&gt;
     *      &lt;/div&gt;
     *  &lt;/div&gt;
     * //以下代码放在body的onload函数里
     * var config = {
     *          data:testData,
     *          startIndex:0
     *      }
     *  var album = new giant.ui.album(config);
     * });
     * </pre>
     */
    giant.ui.album = function(options) {
        opts = $.extend({}, giant.ui.album.defaults, options);
        if (opts.data && opts.data.length > 0) {
            _init();
        } else
        {
            alert("该相册不存在照片");
        }
    };
    function _init() {
        datas = opts.data;
        $(opts.totalNumContainer).text(datas.length);
        var pic = new Picture(datas[opts.startIndex].title, datas[opts.startIndex].remark, opts.startIndex, datas[opts.startIndex].smallImageSrc, datas[opts.startIndex].bigImageSrc,datas[opts.startIndex].id);
        pic.show();
        _eventBind();
    }
    /**
     *Picture类
     *@private
     *@constructor
     *@returns {Picture}
     *@param {String} title 图片标题
     *@param {String} remark 图片描述
     *@param {String} currentIndex 当前图片索引
     *@param {String} imageSrc 小图地址
     *@param {String} bigImageSrc 大图地址
     */
    function Picture(title, remark, currentIndex, smallImageSrc, bigImageSrc,id) {
        this.id= id;
        this.title = title;
        this.remark = remark;
        this.currentIndex = currentIndex;
        this.smallImageSrc = smallImageSrc;
        this.bigImageSrc = bigImageSrc;
        this.dataLength = datas.length;
        this.nextIndex = currentIndex < this.dataLength - 1 ? currentIndex + 1 : 0;
        this.prevIndex = currentIndex == 0 ? this.dataLength - 1 : currentIndex - 1;
        this.auto = null;
        activeNumber = (opts.smallListNum % 2 == 0 ? parseInt(opts.smallListNum / 2) - 1 : parseInt(opts.smallListNum / 2));
        alert(this.currentIndex);
        this.nextDownIndex = this.currentIndex + parseInt(opts.smallListNum / 2) + 1;
        if (this.nextDownIndex > this.dataLength - 1) {
            this.nextDownIndex -= this.dataLength;
        }
        if (this.nextDownIndex > this.dataLength - 1) {
            this.nextDownIndex -= this.dataLength;
        }
        var lowerNumber = (opts.smallListNum % 2 == 0 ? parseInt(opts.smallListNum / 2) : parseInt(opts.smallListNum / 2)) + 1;
        if (this.currentIndex - lowerNumber >= 0) {
            this.prevUpIndex = this.currentIndex - lowerNumber;
        } else {
            this.prevUpIndex = this.currentIndex - lowerNumber + this.dataLength;
        }
    }
    /**
     * 获取小图数组。
     * @returns {Array} 返回存放Picture的数组
     */
    Picture.prototype.getSmallArray = function() {
        var arr = new Array();
        var picPrev = this,picNext = this;
        arr.push(this);
        for (var i = 0; i < activeNumber; i++) {
            picPrev = picPrev.getPrev();
            picNext = picNext.getNext();
            arr.unshift(picPrev);
            arr.push(picNext);
        }
        if (opts.smallListNum % 2 == 0) {
            arr.push(picNext.getNext());
        }
        return arr;
    };
    /**
     * 返回当前图的下一张图对象。
     * @returns {Picture}返回Picture的一个对象
     */
    Picture.prototype.getNext = function() {
        return new Picture(datas[this.nextIndex].title, datas[this.nextIndex].remark, this.nextIndex, datas[this.nextIndex].smallImageSrc, datas[this.nextIndex].bigImageSrc,datas[this.nextIndex].id);
    };
    /**
     * 返回当前图的上一张图对象。
     * @returns {Picture}返回Picture的一个对象
     */
    Picture.prototype.getPrev = function() {
        return new Picture(datas[this.prevIndex].title, datas[this.prevIndex].remark, this.prevIndex, datas[this.prevIndex].smallImageSrc, datas[this.prevIndex].bigImageSrc, datas[this.prevIndex].id);
    };
    /**
     * 返回下一页图对象
     * @returns {Picture}返回Picture的一个对象
     */
    Picture.prototype.getNextDown = function() {

        return new Picture(datas[this.nextDownIndex].title, datas[this.nextDownIndex].remark, this.nextDownIndex, datas[this.nextDownIndex].smallImageSrc, datas[this.nextDownIndex].bigImageSrc,datas[this.nextDownIndex].id);
    };
    /**
     * 返回上一页图对象
     * @returns {Picture}返回Picture的一个对象
     */
    Picture.prototype.getPrevUp = function() {
        return new Picture(datas[this.prevUpIndex].title, datas[this.prevUpIndex].remark, this.prevUpIndex, datas[this.prevUpIndex].smallImageSrc, datas[this.prevUpIndex].bigImageSrc,datas[this.prevUpIndex].id);
    };
    /**
     * 展示图片
     */
    Picture.prototype.show = function() {
        pictureArr = this.getSmallArray();
        $(opts.currentNumContainer).text(this.currentIndex);
        var str = [];
        //加小图
        for (var i = 0; i < pictureArr.length; i++) {
            if (i == activeNumber) {
                str.push("<li class='" + opts.smallImageActiveClass + "'><a href='javascript:void(1)' class='group-p-pic'><img alt=\"" + pictureArr[i].title + "\" src=\"" + pictureArr[i].smallImageSrc + "\"  \/></a></li>");
            }
            else {
                str.push("<li><a href='javascript:void(1)' class='group-p-pic'><img alt=\"" + pictureArr[i].title + "\" src=\"" + pictureArr[i].smallImageSrc + "\"  \/></a></li>");
            }
        }
        $(opts.smallImageContainer).append(str.join(''));
        this._preLoadBigImage();
        $(opts.bigImage).attr("src", pictureArr[activeNumber].bigImageSrc).show();
    };
    /**
     *向下滚动
     *@param {Number} num,滚动几张图片
     */
    Picture.prototype.scrollDown = function(num) {
        if (num > 0) {
            var pic = this.getNextDown();
            var str = [];
            for (var i = 0; i < num; i++)
            {
                str.push("<li><a href='javascript:void(1)' class='group-p-pic'><img alt=\"" + pic.title + "\" src=\"" + pic.smallImageSrc + "\"  \/></a></li>");
                pictureArr.push(pic);
                pictureArr.shift();
                if (i < num - 1)
                {
                    pic = pic.getNext();
                }
            }
            $(opts.smallImageContainer).append(str.join(''));
            this._preLoadBigImage();
            var width = $(opts.smallImageContainer + " li").outerWidth(true) * num;
            //滚动开始
            isScroll = true;
            $(opts.smallImageContainer).animate({left:"-" + width}, opts.smallImageScrollSpeed, function() {
                for (i = 0; i < num; i++)
                {
                    $(opts.smallImageContainer + " li:first-child").remove();
                }
                $(opts.smallImageContainer).css("left", "0px");
                _eventBind();
                _resetActive(activeNumber);
                //结束滚动
                isScroll = false;
            });
        }
    };
    /**
     *向上滚动
     *@param {Number} num,滚动几张图片
     */
    Picture.prototype.scrollUp = function(num) {
        if (num > 0) {
            var pic = this.getPrevUp();
            var str = [];
            for (var i = 0; i < num; i++)
            {
                str.unshift("<li><a href='javascript:void(1)' class='group-p-pic'><img alt=\"" + pic.title + "\" src=\"" + pic.smallImageSrc + "\"  \/></a></li>");
                pictureArr.unshift(pic);
                pictureArr.pop();
                if (i < num - 1)
                {
                    pic = pic.getPrev();
                }
            }
            var width = $(opts.smallImageContainer + " li").outerWidth(true) * num;
            $(opts.smallImageContainer).prepend(str.join(''));
            $(opts.smallImageContainer).css("left","-"+width+"px");
            this._preLoadBigImage();
            $(opts.smallImageContainer).animate({left:"0"}, opts.smallImageScrollSpeed, function() {
                for (i = 0; i < num; i++)
                {
                    $(opts.smallImageContainer + " li:last-child").remove();
                }
                _eventBind();
                _resetActive(activeNumber);
                isScroll = false;
            });
        }

    };
    //相关事件绑定
    function _eventBind() {
        $(opts.smallImageContainer + " li").each(function(index) {
            $(this).unbind("click").bind("click", function() {
                //若刷新页面
                if (opts.isRefresh) {
                    //获取点击图片的索引
                    var myIndex = index - activeNumber + pictureArr[activeNumber].currentIndex;
                    myIndex = myIndex >= pictureArr[activeNumber].dataLength ? myIndex - pictureArr[activeNumber].dataLength : myIndex;
                    myIndex = myIndex < 0 ? pictureArr[activeNumber].dataLength + myIndex : myIndex;
                    var str = window.location.href ;
                    str = str.split("?")[0];
                    str += "?" + myIndex;
                    window.location.href = str;
                } else {
                    if (!isScroll) {
                        if (index > activeNumber) {
                            pictureArr[activeNumber].scrollDown(index - activeNumber);
                        }
                        else if (index < activeNumber) {
                            pictureArr[activeNumber].scrollUp(activeNumber - index);
                        }
                    }
                }
            });
        });
        $(opts.btnNextPage).unbind("click").bind("click", function() {
            if (!isScroll) {
                pictureArr[activeNumber].scrollDown(opts.smallListNum);
            }
        });
        $(opts.btnPrevPage).unbind("click").bind("click", function() {
            if (!isScroll) {
                pictureArr[activeNumber].scrollUp(opts.smallListNum);
            }
        });
        $(opts.btnNextImage).unbind("click").bind("click", function() {
            if (!isScroll) {
                pictureArr[activeNumber].scrollDown(1);
            }
        });
        $(opts.btnPrevImage).unbind("click").bind("click", function() {
            if (!isScroll) {
                pictureArr[activeNumber].scrollUp(1);
            }
        });
    }
     Picture.prototype._preLoadBigImage=function() {
        //加大图
        $(opts.loading).css("opacity", "0.6");
        var time = setTimeout(function() {
            $(opts.bigImage).attr("src", pictureArr[activeNumber].smallImageSrc).css("height", "");
            $(opts.loading).show();
        }, 500);

        var img = new Image();
        //加图片属性
        img.onload = function() {
            if (time != null) {
                clearTimeout(time);
            }
            $(opts.loading).hide();
            var sizeArr = _getImageSize(this.width, this.height, opts.bigImageMaxWidth, opts.bigImageMaxHeight);
            $(opts.bigImage).css("width", sizeArr[0] + "px").css("height", sizeArr[1] + "px").attr("src", pictureArr[activeNumber].bigImageSrc);
        };
        img.src = pictureArr[activeNumber].bigImageSrc;
        $(opts.titleContainer).html(pictureArr[activeNumber].title);
        $(opts.reamrkContainer).html(pictureArr[activeNumber].remark);
        $(opts.currentNumContainer).text(pictureArr[activeNumber].currentIndex + 1);
        if($.isFunction(opts.changeCallBack)){
            opts.changeCallBack.call(pictureArr[activeNumber]);	
        }
       
    }
    function _resetActive(activeNumber) {
        $(opts.smallImageContainer + " li").removeClass(opts.smallImageActiveClass);
        $(opts.smallImageContainer + " li").eq(activeNumber).addClass(opts.smallImageActiveClass);
    }
    function _getImageSize(width, height, maxWidth, maxHeight) {
        var vWidth, vHeight;
        if (width > maxWidth) {
            vWidth = maxWidth;
            vHeight = (maxWidth / width) * height;
        } else {
            vWidth = width;
            vHeight = height;
        }
        if (vHeight > maxHeight) {
            vHeight = maxHeight;
            vWidth = (maxHeight / height) * width;
        }
        return [vWidth,vHeight];
    }
    /**
     * 默认参数
     * @default data ==> JSON数据<br />
     *          startIndex ==> 从data的第几个小标处开始显示图片，默认为0，即第一张图片开始<br />
     *          smallListNum ==> 小图的张数<br />
     *          bigImage ==> 大图容器<br />
     *          bigImageMaxWidth  ==> 大图最大宽度,默认为800，单位为像素<br />
     *          bigImageMaxHeight ==> 大图最大高度度,默认为600，单位为像素<br />
     *          smallImageContainer ==> 小图容器<br />
     *          smallImageMaxWidth ==> 小图图最大宽度,默认为80，单位为像素<br />
     *          smallImageMaxHeight ==> 小图最大高度,默认为80，单位为像素<br />
     *          smallImageActiveClass ==> 小图选中的样式.默认为active<br />
     *          smallImageScrollSpeed ==> 小图滚动所需要的时间,默认为500,单位为毫秒<br />
     *          loading==>loading 条
     *          btnNextPage ==> 小图中下一页按钮<br />
     *          btnPrevPage ==> 小图中上一页按钮<br />
     *          titleContainer ==> 存放图片标题容器<br />
     *          remarkContainer ==> 存放图片描述容器<br />
     *          isRefresh ==> 切换图片的时候是否刷新页面,默认为不刷新,刷新则为true<br />
     *          changeCallBack==>图片变换之后的回调函数
     */
    giant.ui.album.defaults = {
        data:null,
        startIndex:0,
        smallListNum:5,
        bigImage:"#big_image",
        bigImageMaxWidth:650,
        bigImageMaxHeight:500,
        smallImageContainer:"#small_image_container",
        smallImageMaxWidth:100,
        smallImageMaxHeight:75,
        smallImageActiveClass:"active",
        smallImageScrollSpeed:500,
        btnNextPage:"#btn_right_album" ,
        btnPrevPage:"#btn_left_album" ,
        btnNextImage:"#btn_next",
        btnPrevImage:"#btn_prev",
        loading:"#image-loading",
        titleContainer:"#img_title_container",
        reamrkContainer:"#img_remark_container",
        currentNumContainer:"#current_num",
        totalNumContainer:"#total_num",
        changeCallBack:null,
        isRefresh:false
    };
})(jQuery);